package cn.wizzer.app.crown.commons.websocket.main.filter;

import cn.wizzer.app.crown.commons.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.crown.commons.websocket.main.base.NettyRouter;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.util.ClassUtil;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 22099
 */
public abstract class BaseNettyFilter {
    /**
     * class-实例
     */
    private static final Map<Class, BaseNettyFilter> FILTERS = new HashMap<>();

    static {
        //启动注入
        //启动注入 （按理说应该写个IOC容器，不过此处为简易封装就免了，谁闲着没事也可以集成到spring或者nutz
        String thisPackageName = BaseNettyFilter.class.getPackage().getName();
        List<Class<?>> classListByAnnotation = ClassUtil.getClassListByAnnotation(thisPackageName.substring(0, thisPackageName.indexOf(".main")), NettyFilter.class,true);

        for (Class<?> aClass : classListByAnnotation) {
            try {
                //创建实例
                aClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    protected BaseNettyFilter() {
        NettyFilter nettyFilter = this.getClass().getAnnotation(NettyFilter.class);
        if (nettyFilter == null) {
            Result.breakWith(String.format("Non conforming class:%s\n Cause By Annotation NettyFilter not found on the class;", this.getClass()));
        }
        FILTERS.put(this.getClass(),this);
    }

    public static BaseNettyFilter instance(Class<? extends BaseNettyFilter> clazz){
        return FILTERS.get(clazz);
    }

    public static Collection<BaseNettyFilter> instances() {
        return FILTERS.values();
    }

    /**
     * 业务逻辑执行前校验
     * return null则下一项否则返回该方法返回值
     * @param router
     * @param action
     * @return
     */
    public abstract Object doFilter(NettyRouter router, BaseNettyAction action);

}
